package com.zhiyizhen.callnumber.websocket;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.zhiyizhen.callnumber.common.LogUtil;
import com.zhiyizhen.callnumber.component.bean.SocketResultBean;
import com.google.gson.Gson;

import okhttp3.Response;
import okhttp3.WebSocket;

public class WebSocketService extends Service {
    private static final String TAG = "WebSocketService";
    public static final String ACTION_WEBSOCKET_MESSAGE = "action_websocket_message";
    public static final String EXTRA_MESSAGE = "extra_message";
    private static final String CHANNEL_ID = "WebSocketServiceChannel";
    private static final int NOTIFICATION_ID = 1;
    private WebSocketManager webSocketManager;
    private boolean isServiceRunning = false;
    private final IBinder binder = new LocalBinder();
    public class LocalBinder extends Binder {
        public WebSocketService getService() {
            // 返回当前服务实例，使Activity可以调用服务的公共方法
            return WebSocketService.this;
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.d(TAG + "服务创建");
        isServiceRunning = true;
        createNotificationChannel();
        
        // 初始化WebSocket管理器，替换为你的WebSocket服务器地址
        webSocketManager = WebSocketManager.getInstance();
        
        // 设置WebSocket监听器
        webSocketManager.setListener(new okhttp3.WebSocketListener() {
            @Override
            public void onOpen(@NonNull WebSocket webSocket, @NonNull Response response) {
                super.onOpen(webSocket, response);
                LogUtil.d(TAG + "WebSocket连接已打开");
                // 连接成功后发送设备上线请求
//                webSocketManager.sendConnectSuccessMessage();
            }

            @Override
            public void onMessage(@NonNull WebSocket webSocket, @NonNull String text) {
                super.onMessage(webSocket, text);
                LogUtil.d(TAG + "收到消息: " + text);
                // 这里可以处理收到的消息，如发送广播更新UI等
                SocketResultBean resultBean = new Gson().fromJson(text, SocketResultBean.class);
                if (resultBean.getData() != null && resultBean.getData().getMessage() != null) {
                    LogUtil.d(TAG + "收到消息: " + resultBean.getData().getMessage());
                    sendMessageBroadcast(resultBean.getData().getMessage());
                }
            }
        });
        
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.d(TAG + "Service started");

        // 启动前台服务
//        Notification notification = createNotification();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
//            startForeground(NOTIFICATION_ID, notification,
//                    ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
//        } else {
//            startForeground(NOTIFICATION_ID, notification);
//        }

        // 连接WebSocket
        if (!webSocketManager.isConnected()) {
            webSocketManager.connect();
        }

        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder; // 返回Binder实例
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.d(TAG + "服务销毁");
        isServiceRunning = false;
        // 断开WebSocket连接
        if (webSocketManager != null) {
            webSocketManager.disconnect();
        }
    }

    // 创建通知渠道（Android O及以上需要）
    private void createNotificationChannel() {
        NotificationChannel serviceChannel = new NotificationChannel(
                CHANNEL_ID,
                "WebSocket服务",
                NotificationManager.IMPORTANCE_LOW
        );
        NotificationManager manager = getSystemService(NotificationManager.class);
        if (manager != null) {
            manager.createNotificationChannel(serviceChannel);
        }
    }

    // 创建通知
    private Notification createNotification() {
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("WebSocket连接中")
                .setContentText("保持与服务器的实时通信")
                .setSmallIcon(android.R.drawable.ic_menu_info_details)
                .build();
    }

    // 发送消息到Activity
    public void sendMessageBroadcast(String message) {
        Intent intent = new Intent(ACTION_WEBSOCKET_MESSAGE);
        intent.putExtra(EXTRA_MESSAGE, message);
        // 限制广播只在本应用内传播
        intent.setPackage(getPackageName());
        sendBroadcast(intent);
        LogUtil.d(TAG + "发送消息广播: " + message);
    }


    // 提供外部调用的安全停止方法
    public void stopServiceSafely() {
        if (isServiceRunning) {
            LogUtil.d(TAG +"Stopping service safely");
            stopSelf();
        }
    }
}
